<template>
  <div class="timestamp-tool">
    <Breadcrumb />
    
    <div class="tool-header">
      <div class="container">
        <h1>时间戳转换工具</h1>
        <div class="subtitle-group">
          <p class="subtitle">在线时间戳与日期格式互转工具</p>
        </div>
      </div>
    </div>

    <div class="tool-content">
      <div class="container">
        <div class="conversion-panel">
          <div class="current-timestamp">
            <h3>当前时间</h3>
            <div class="timestamp-display">
              <span class="value">{{ currentTimestamp }}</span>
              <button class="action-btn" @click="copyToClipboard(currentTimestamp.toString())">
                {{ copiedTimestamp ? '已复制' : '复制' }}
              </button>
            </div>
            <div class="formatted-date">
              <span class="value">{{ currentFormattedDate }}</span>
              <button class="action-btn" @click="copyToClipboard(currentFormattedDate)">
                {{ copiedDate ? '已复制' : '复制' }}
              </button>
            </div>
          </div>

          <div class="convert-section">
            <h3>时间戳转换</h3>
            <div class="input-group">
              <input 
                type="text" 
                v-model="inputTimestamp" 
                placeholder="输入时间戳..."
                class="custom-input"
              >
              <button class="action-btn" @click="convertToDatetime">转换</button>
            </div>
            <div v-if="convertedDatetime" class="result">
              <h4>转换结果</h4>
              <p class="result-value">{{ convertedDatetime }}</p>
            </div>
          </div>

          <div class="convert-section">
            <h3>日期时间转换</h3>
            <div class="input-group">
              <input 
                type="text" 
                v-model="inputDatetime" 
                placeholder="输入日期时间..."
                class="custom-input"
              >
              <button class="action-btn" @click="convertToTimestamp">转换</button>
            </div>
            <div v-if="convertedTimestamp">
              <h4>转换结果</h4>
              <p>{{ convertedTimestamp }}</p>
            </div>
          </div>

          <div class="control-buttons">
            <button @click="startUpdating">开始</button>
            <button @click="stopUpdating">结束</button>
          </div>

          <hr class="separator" />

          <div class="code-snippets">
            <h3>代码示例</h3>
            <div class="example-tabs">
              <button 
                class="tab-btn"
                :class="{ active: activeExample === '编程语言' }" 
                @click="activeExample = '编程语言'"
              >
                编程语言
              </button>
              <button 
                class="tab-btn"
                :class="{ active: activeExample === '数据库' }" 
                @click="activeExample = '数据库'"
              >
                数据库
              </button>
            </div>
            <div class="examples">
              <table v-if="activeExample === '编程语言'">
                <thead>
                  <tr>
                    <th>语言</th>
                    <th>实现代码</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(code, lang) in codeExamples.languages" :key="lang">
                    <td>{{ lang }}</td>
                    <td><pre><code>{{ code }}</code></pre></td>
                  </tr>
                </tbody>
              </table>
              <table v-if="activeExample === '数据库'">
                <thead>
                  <tr>
                    <th>数据库</th>
                    <th>实现代码</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(code, db) in codeExamples.databases" :key="db">
                    <td>{{ db }}</td>
                    <td><pre><code>{{ code }}</code></pre></td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import Breadcrumb from '@/components/Breadcrumb.vue'

const currentTimestamp = ref(Math.floor(Date.now() / 1000))
const currentFormattedDate = computed(() => {
  const date = new Date(currentTimestamp.value * 1000)
  return date.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }).replace(/\//g, '-')
})
const inputTimestamp = ref('')
const convertedDatetime = ref('')
const inputDatetime = ref('')
const convertedTimestamp = ref('')

const activeExample = ref('编程语言')
const copiedTimestamp = ref(false)
const copiedDate = ref(false)

const codeExamples = {
  languages: {
    JavaScript: `Date.now() / 1000`,
    Python: `int(time.time())`,
    Java: `System.currentTimeMillis() / 1000`,
    CSharp: `DateTimeOffset.Now.ToUnixTimeSeconds()`,
    Ruby: `Time.now.to_i`,
    PHP: `time()`,
    Go: `time.Now().Unix()`,
    Swift: `Int(Date().timeIntervalSince1970)`
  },
  databases: {
    MySQL: `SELECT UNIX_TIMESTAMP();`,
    PostgreSQL: `SELECT EXTRACT(EPOCH FROM NOW());`,
    SQLite: `SELECT strftime('%s', 'now');`,
    Oracle: `SELECT (SYSDATE - TO_DATE('1970-01-01', 'YYYY-MM-DD')) * 86400 FROM DUAL;`,
    SQLServer: `SELECT DATEDIFF(SECOND, '1970-01-01', GETUTCDATE());`
  }
}

// 定时更新当前时间戳
let intervalId: number | undefined

const startUpdating = () => {
  if (!intervalId) {
    intervalId = window.setInterval(() => {
      currentTimestamp.value = Math.floor(Date.now() / 1000)
    }, 1000)
  }
}

const stopUpdating = () => {
  if (intervalId) {
    clearInterval(intervalId)
    intervalId = undefined
  }
}

onMounted(() => {
  startUpdating()
})

onUnmounted(() => {
  stopUpdating()
})

// 复制到剪贴板
const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text)
    console.log('已复制到剪贴板:', text)
    if (text === currentTimestamp.value.toString()) {
      copiedTimestamp.value = true
      setTimeout(() => copiedTimestamp.value = false, 2000)
    } else if (text === currentFormattedDate.value) {
      copiedDate.value = true
      setTimeout(() => copiedDate.value = false, 2000)
    }
  } catch (error) {
    console.error('复制失败:', error)
  }
}

// 时间戳转换为日期时间
const convertToDatetime = () => {
  if (!inputTimestamp.value) return
  const timestamp = parseInt(inputTimestamp.value, 10)
  if (isNaN(timestamp)) {
    alert('请输入有效的时间戳')
    return
  }
  const date = new Date(timestamp * 1000)
  convertedDatetime.value = date.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }).replace(/\//g, '-')
}

// 日期时间转换为时间戳
const convertToTimestamp = () => {
  if (!inputDatetime.value) {
    alert('请输入有效的日期时间')
    return
  }
  const date = new Date(inputDatetime.value)
  if (isNaN(date.getTime())) {
    alert('请输入有效的日期时间')
    return
  }
  convertedTimestamp.value = Math.floor(date.getTime() / 1000).toString()
}
</script>

<style scoped lang="scss">
.timestamp-tool {
  .tool-header {
    background: linear-gradient(135deg, var(--primary-color), var(--hover-color));
    padding: 20px 0;
    color: white;
    text-align: center;
    margin-top: -1px;

    h1 {
      font-size: 1.8rem;
      margin-bottom: 0.5rem;
    }

    .subtitle-group {
      display: flex;
      flex-direction: column;
      gap: 8px;
      align-items: center;

      .subtitle {
        font-size: 0.95rem;
        opacity: 0.9;
        background: rgba(255, 255, 255, 0.1);
        padding: 6px 16px;
        border-radius: 20px;
        backdrop-filter: blur(10px);
      }
    }
  }

  .tool-content {
    padding: 40px 0;

    .conversion-panel {
      background: white;
      border-radius: 12px;
      box-shadow: 0 5px 15px rgba(0,0,0,0.1);
      padding: 30px;
      display: flex;
      flex-direction: column;
      gap: 40px;

      .current-timestamp, .convert-section, .code-snippets {
        h3 {
          margin-bottom: 15px;
          color: var(--text-color);
        }

        .timestamp-display, .formatted-date, .convert-section {
          display: flex;
          align-items: center;
          gap: 10px;
          margin-bottom: 10px;

          .value {
            font-size: 1.2rem;
            color: var(--primary-color);
            font-weight: 500;
            flex: 1;
          }
        }

        .input-group {
          display: flex;
          gap: 10px;
          align-items: center;

          .custom-input {
            flex: 1;
            min-width: 200px;
          }
        }

        h4 {
          margin-top: 10px;
          color: var(--text-color);
        }

        p {
          color: #666;
        }

        .example-tabs {
          display: flex;
          justify-content: center;
          gap: 20px;
          margin-bottom: 15px;

          span {
            cursor: pointer;
            font-size: 1rem;
            color: #666;
            transition: color 0.3s ease;

            &.active {
              color: var(--primary-color);
              font-weight: bold;
            }

            &:hover {
              color: var(--hover-color);
            }
          }
        }

        .examples {
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 20px;
        }

        table {
          width: 100%;
          border-collapse: collapse;
          margin-top: 15px;

          th, td {
            border: 1px solid #ddd;
            padding: 10px;
            text-align: left;
            font-size: 0.9rem;
          }

          th {
            background: #f8f9fa;
            color: var(--text-color);
          }

          pre {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 6px;
            font-size: 0.85rem;
            overflow-x: auto;
            margin: 0;
          }
        }
      }

      .control-buttons {
        display: flex;
        gap: 10px;

        button {
          width: 80px;
          padding: 8px 0;
          border: none;
          background: var(--primary-color);
          color: white;
          border-radius: 6px;
          cursor: pointer;
          transition: all 0.3s ease;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

          &:hover {
            background: var(--hover-color);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            transform: translateY(-2px);
          }

          &:active {
            transform: translateY(0);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
          }
        }
      }

      .separator {
        border: none;
        border-top: 1px solid #eee;
        margin: 20px 0;
      }
    }
  }
}

.action-btn {
  min-width: 80px;
  padding: 8px 16px;
  border: none;
  background: var(--primary-color);
  color: white;
  border-radius: 6px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  &:hover {
    background: var(--hover-color);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    transform: translateY(-2px);
  }

  &:active {
    transform: translateY(0);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
}

.copy-btn {
  padding: 6px 12px;
  border: 1px solid var(--primary-color);
  background: transparent;
  color: var(--primary-color);
  border-radius: 4px;
  font-size: 0.9rem;
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    background: var(--primary-color);
    color: white;
  }

  .copied {
    color: #4CAF50;
  }
}

.custom-input {
  flex: 1;
  padding: 10px 16px;
  border: 2px solid #e0e0e0;
  border-radius: 6px;
  font-size: 1rem;
  transition: all 0.2s ease;

  &:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(var(--primary-color-rgb), 0.1);
  }
}

.result {
  margin-top: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;

  h4 {
    color: #666;
    margin-bottom: 8px;
  }

  .result-value {
    color: var(--primary-color);
    font-size: 1.1rem;
    font-weight: 500;
  }
}

.example-tabs {
  background: #f8f9fa;
  padding: 4px;
  border-radius: 8px;
  display: inline-flex;
  gap: 4px;
  margin-bottom: 20px;

  .tab-btn {
    padding: 8px 16px;
    border: none;
    background: transparent;
    color: #666;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.2s ease;

    &.active {
      background: white;
      color: var(--primary-color);
      font-weight: 500;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    &:hover:not(.active) {
      background: rgba(255,255,255,0.5);
    }
  }
}

table {
  th {
    background: #f8f9fa;
    font-weight: 500;
    color: #333;
  }

  td {
    pre {
      background: #f8f9fa;
      padding: 12px;
      border-radius: 6px;
      font-family: 'Fira Code', monospace;
      font-size: 0.9rem;
      
      code {
        color: #333;
      }
    }
  }
}
</style>